package manager;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

public class SessionManager {

	private static Map<String, HttpSession> mSessions = new HashMap<String, HttpSession>();
	
	public static synchronized void addSession(HttpSession session) {
		String username = (String)session.getAttribute("username");
		if (username == null) {
			return;
		}
		
		if (mSessions.containsKey(username)) {
			HttpSession oldSession = mSessions.get(username);
			mSessions.remove(username);
			oldSession.invalidate();
		}
		
		mSessions.put(username, session);
		System.out.println("addSession() for " + username);
		
	}
	
		
	public static synchronized void removeSession(HttpSession session) {
		String username = (String)session.getAttribute("username");
		if (username == null) {
			return;
		}
		
		mSessions.remove(username);
		System.out.println("removeSession() for " + username);
	}
	
	public static synchronized void invalidateSession(String username) {
		HttpSession session = mSessions.get(username);
		if (session == null) {
			return;
		}
		
		removeSession(session);
		session.invalidate();	
		System.out.println("invalidateSession() for " + username);
	}
	
	public static synchronized int getNumSessions() {
		return mSessions.size();
	}
}
